package com.zhq.zhq_blog.module.blog.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.zhq.zhq_blog.R
import com.zhq.zhq_blog.base.BaseIntentBean
import com.zhq.zhq_blog.base.BaseVMActivity
import com.zhq.zhq_blog.base.Constant
import com.zhq.zhq_blog.databinding.ActivityBlogDetailBinding
import com.zhq.zhq_blog.databinding.CommentDialogLayoutBinding
import com.zhq.zhq_blog.module.blog.adapter.CommentExpandAdapter
import com.zhq.zhq_blog.module.blog.bean.BlogPageListResult
import com.zhq.zhq_blog.module.blog.bean.CommentBeanResult
import com.zhq.zhq_blog.module.blog.bean.CommentDetailBean
import com.zhq.zhq_blog.module.blog.bean.ReplyDetailBean
import com.zhq.zhq_blog.module.blog.viewmodel.BlogDetailViewModel
import com.zhq.zhq_blog.module.bus.UpdateBlogEvent
import com.zhq.zhq_blog.net.common.CommonResultBean
import com.zhq.zhq_blog.store.UserManager
import com.zhq.zhq_blog.util.GlideUtil
import com.zhq.zhq_blog.util.log.LogUtil
import com.zhq.zhq_blog.util.zhq.toast

//这里不写收藏，点赞功能了，太麻烦。外边的列表已经实现了一遍了
class BlogDetailActivity : BaseVMActivity<BlogDetailViewModel>(), View.OnClickListener {
    val mViewBinding by lazy { ActivityBlogDetailBinding.inflate(layoutInflater) }
    var intentBean: IntentBean = IntentBean(0)
    var adapter: CommentExpandAdapter? = null
    var commentBean: CommentBeanResult? = null
    var commentsList: List<CommentDetailBean>? = null
    var dialog: BottomSheetDialog? = null
    lateinit var blog: CommonResultBean<BlogPageListResult.Data>

    companion object {

        fun startActivity(context: Context, intentBean: IntentBean) {
            val intent = Intent(context, BlogDetailActivity::class.java)
            intent.putExtra(Constant.IntentKey.IntentBean, intentBean)
            context.startActivity(intent)
        }

        /**
         * 通过点击评论启动博客详情
         */
        fun startActivityComment(context: Context, intentBean: IntentBean) {
            val intent = Intent(context, BlogDetailActivity::class.java)
            intent.putExtra(Constant.IntentKey.IntentBean, intentBean)
            intent.putExtra(Constant.IntentKey.isClickComment, true)
            context.startActivity(intent)
        }

        /**
         * view是需要共享效果的view
         * 否则不会报错,但没有动画效果
         */
        fun startActivityForTransition(
            activity: Activity, intentBean: IntentBean,
            view_title: View, view_user: View, view_content: View
        ) {
            //共享元素跳转
            val i = Intent(activity, BlogDetailActivity::class.java)
            i.putExtra(Constant.IntentKey.IntentBean, intentBean)
            val pair1 = androidx.core.util.Pair(view_title, "SHARE_VIEW_1")
            val pair2 = androidx.core.util.Pair(view_user, "SHARE_VIEW_2")
            val pair3 = androidx.core.util.Pair(view_content, "SHARE_VIEW_3")
            val optionsCompat: ActivityOptionsCompat =
                ActivityOptionsCompat.makeSceneTransitionAnimation(activity, pair1, pair2, pair3)
            // ActivityCompat是android支持库中用来适应不同android版本的
            ActivityCompat.startActivity(activity, i, optionsCompat.toBundle())
        }

        data class IntentBean(var blogId: Int) : BaseIntentBean()
    }


    override fun setContentView() {
        setContentView(mViewBinding.root)

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding.ivCollect.setOnClickListener(this)
        mViewBinding.ivPraise.setOnClickListener(this)
        mViewBinding.detailPageDoComment.setOnClickListener(this)

        //如果通过点击评论按钮启动博客时则显示评论框
        val isClickComment = intent.extras?.get(Constant.IntentKey.isClickComment)
        if (isClickComment != null && isClickComment as Boolean) {
            showCommentDialog()
        }

        parseIntent<IntentBean>()?.apply {
            intentBean = this
        }
        initBus()
        mViewBinding.layoutTitle.ivBack.setOnClickListener {
            finish()
        }
        mViewBinding.tvEdit.setOnClickListener {
            EditBlogActivity.startActivity(
                context,
                EditBlogActivity.Companion.IntentBean(intentBean.blogId)
            )
        }
        netDetail()

    }

    private fun initBus() {
        //监听事件总线的消息
        LiveEventBus
            .get(UpdateBlogEvent::class.java)
            .observe(this) {
                netDetail()
            }
    }

    override fun onClick(view: View) {
        if (view.id == mViewBinding.detailPageDoComment.id) {
            showCommentDialog()
        } else if (view.id == mViewBinding.ivCollect.id) {
            if (blog.data?.isMyCollected == 0) {
                netCollect(intentBean.blogId, true)
                mViewBinding.ivCollect.setImageResource(R.drawable.ic_collected)
            } else {
                netCollect(intentBean.blogId, false)
                mViewBinding.ivCollect.setImageResource(R.drawable.ic_uncollect)
            }
        } else if (view.id == mViewBinding.ivPraise.id) {
            if (blog.data?.isMyPraised == 0) {
                netPraise(intentBean.blogId, true)
                mViewBinding.ivPraise.setImageResource(R.drawable.ic_praised)
            } else {
                netPraise(intentBean.blogId, false)
                mViewBinding.ivPraise.setImageResource(R.drawable.ic_unpraise)
            }
        }
    }

    private fun netCollect(blogId: Int, isCollect: Boolean) {
        var type = 1
        if (!isCollect) {
            type = 2
        }
        mViewModel.collect(blogId, type)
            .observe(this) {
                if (it.isServerResultOK()) {
                    if (isCollect) {
                        blog.data?.isMyCollected = 1
                        blog.data?.collectCount = blog.data?.collectCount?.plus(1)!!
                        Log.d(
                            "BlogListFragment",
                            "net_collect: 收藏成功，count=" + blog.data?.collectCount
                        )
                        toast("收藏成功")
                    } else {
                        blog.data?.isMyCollected = 0
                        blog.data?.collectCount = blog.data?.collectCount?.minus(1)!!
                        Log.d(
                            "BlogListFragment",
                            "net_collect: 取消收藏成功，count=" + blog.data?.collectCount
                        )
                        toast("已取消收藏")
                    }
                } else {
                    toast(it.msg)
                }

            }
    }

    private fun netPraise(blogId: Int, isPraise: Boolean) {
        var type = 1
        if (!isPraise) {
            type = 2
        }
        mViewModel.praise(blogId, type)
            .observe(this) {
                if (it.isServerResultOK()) {
                    if (isPraise) {
                        blog.data?.isMyPraised = 1
                        blog.data?.praiseCount = blog.data?.praiseCount?.plus(1)!!
                        Log.d(
                            "BlogListFragment",
                            "net_praise: 点赞成功，count=" + blog.data?.praiseCount
                        )
                        toast("点赞成功")
                    } else {
                        blog.data?.isMyPraised = 0
                        blog.data?.praiseCount = blog.data?.praiseCount?.minus(1)!!
                        Log.d(
                            "BlogListFragment",
                            "net_praise: 取消点赞成功，count=" + blog.data?.praiseCount
                        )
                        toast("已取消点赞")
                    }
                } else {
                    toast(it.msg)
                }

            }
    }

    private fun netDetail() {
        mViewModel.getDetail(intentBean.blogId).observe(this) {
            if (it.isServerResultOK()) {
                blog = it
                generateTestData()
                it.data?.let {
                    mViewBinding.layoutTitle.tvTitle.text = it.title
                    GlideUtil.loadHead(activity, it.user.iconUrl, mViewBinding.ivIcon)
                    mViewBinding.tvUsername.text = it.user.username
                    mViewBinding.tvDate.text = it.createTime
                    configWebView(it.content)
                    if (it.userId == UserManager.getUserInfo().id) {
                        mViewBinding.tvEdit.visibility = View.VISIBLE
                    } else {
                        mViewBinding.tvEdit.visibility = View.GONE
                    }

                    if (it.isMyCollected == 0) {
                        mViewBinding.ivCollect.setImageResource(R.drawable.ic_uncollect)
                    } else {
                        mViewBinding.ivCollect.setImageResource(R.drawable.ic_collected)
                    }

                    if (it.isMyPraised == 0) {
                        mViewBinding.ivPraise.setImageResource(R.drawable.ic_unpraise)
                    } else {
                        mViewBinding.ivPraise.setImageResource(R.drawable.ic_praised)
                    }

                }
            }
        }
    }

    private fun configWebView(content: String) {
        LogUtil.d("configWebView: 执行")
        val webSettings: WebSettings = mViewBinding.tvContent.settings
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true
        mViewBinding.tvContent.isVerticalScrollBarEnabled = false
        mViewBinding.tvContent.isHorizontalScrollBarEnabled = false
        mViewBinding.tvContent.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    loadMarkdown(content)
                }
            }
        }
        mViewBinding.tvContent.loadUrl("file:///android_asset/markdown.html")
    }

    private fun loadMarkdown(markdown: String) {
        val content = markdown.replace("\n", "\\n").replace("\"", "\\\"")
            .replace("'", "\\'")
        mViewBinding.tvContent.evaluateJavascript("javascript:parseMarkdown(\"$content\");", null)

    }

    /**
     * func:获取评论数据
     */
    private fun generateTestData() {
        LogUtil.d("generateTestData: 运行")
        mViewModel.getCommentDetail(intentBean.blogId).observe(this) {
            if (it.isServerResultOK()) {
                val gson = Gson()
                commentBean = gson.fromJson(gson.toJson(it), CommentBeanResult::class.java)
                LogUtil.d("generateTestData: commentBean=" + commentBean.toString())
                commentsList = commentBean?.data?.list
                initExpandableListView(commentsList!!)
            }
        }
    }

    /**
     * 初始化评论和回复列表
     */
    private fun initExpandableListView(commentList: List<CommentDetailBean>) {
        mViewBinding.detailPageLvComment.setGroupIndicator(null)
        //默认展开所有回复
        adapter = CommentExpandAdapter(
            this,
            commentList, mViewModel, intentBean.blogId
        )
        mViewBinding.detailPageLvComment.setAdapter(adapter)
        for (i in commentList.indices) {
            mViewBinding.detailPageLvComment.expandGroup(i)
        }
        mViewBinding.detailPageLvComment.setOnGroupClickListener { expandableListView, _, groupPosition, _ ->
            val isExpanded = expandableListView.isGroupExpanded(groupPosition)
            LogUtil.d("onGroupClick: 当前的评论id>>>" + commentList[groupPosition].id)
            if (isExpanded) {
                expandableListView.collapseGroup(groupPosition)
            } else {
                expandableListView.expandGroup(groupPosition, true)
            }
            showReplyDialog(groupPosition)
            true
        }
        mViewBinding.detailPageLvComment.setOnChildClickListener { _, _, _, _, _ ->
            toast("点击了回复")
            false
        }
        mViewBinding.detailPageLvComment.setOnGroupExpandListener {
            //toast("展开第"+groupPosition+"个分组");
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * func:弹出评论框
     */
    private fun showCommentDialog() {
        dialog = BottomSheetDialog(this)
        val commentViewBinding = CommentDialogLayoutBinding.inflate(layoutInflater, null, false)
        val commentView = commentViewBinding.root
        val commentText = commentViewBinding.dialogCommentEt
        val btComment = commentViewBinding.dialogCommentBt
        dialog!!.setContentView(commentView)
        /**
         * 解决弹窗显示不全的情况
         */
        val parent = commentView.parent as View
        val behavior = BottomSheetBehavior.from(parent)
        commentView.measure(0, 0)
        behavior.peekHeight = commentView.measuredHeight
        btComment.setOnClickListener {
            val commentContent = commentText.text.toString().trim { it <= ' ' }
            if (!TextUtils.isEmpty(commentContent)) {
                //commentOnWork(commentContent);
                dialog!!.dismiss()
                val detailBean = CommentDetailBean(commentContent)
                adapter!!.addTheCommentData(detailBean)
            } else {
                toast("评论内容不能为空")
            }
        }
        commentText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length > 2) {
                    btComment.setBackgroundColor(Color.parseColor("#FFB568"))
                } else {
                    btComment.setBackgroundColor(Color.parseColor("#D8D8D8"))
                }
            }

            override fun afterTextChanged(editable: Editable) {}
        })
        dialog!!.show()
    }

    /**
     * func:弹出回复框
     */
    private fun showReplyDialog(position: Int) {
        dialog = BottomSheetDialog(this)
        val commentViewBinding = CommentDialogLayoutBinding.inflate(layoutInflater, null, false)
        val commentView = commentViewBinding.root
        val commentText = commentViewBinding.dialogCommentEt
        val btComment = commentViewBinding.dialogCommentBt
        commentText.hint = "回复 " + commentsList!![position].nickName.toString() + " 的评论:"
        dialog!!.setContentView(commentView)
        btComment.setOnClickListener {
            val replyContent = commentText.text.toString().trim { it <= ' ' }
            if (!TextUtils.isEmpty(replyContent)) {
                dialog!!.dismiss()
                val detailBean = ReplyDetailBean(replyContent)
                adapter!!.addTheReplyData(detailBean, position)
                mViewBinding.detailPageLvComment.expandGroup(position)
            } else {
                toast("回复内容不能为空")
            }
        }
        commentText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length > 2) {
                    btComment.setBackgroundColor(Color.parseColor("#FFB568"))
                } else {
                    btComment.setBackgroundColor(Color.parseColor("#D8D8D8"))
                }
            }

            override fun afterTextChanged(editable: Editable) {}
        })
        dialog!!.show()
    }

}